<?
namespace Api\Model
{
	/** XML
	 * SimpleXML 
	**/
	class	XML extends \Api\Model
	{
		private $m_filename = null;
		
		////////////////////////////////////////////
		
		public function __construct($file=null)
		{
			if($file) $this->Open($file);
		}
		public function __destruct(){
			unset($this->_handle);
		}
		
		final public function __initModel($config){}
		
		////////////////////////////////////////////
		
		/** Open
		 * Read XML file and parse
		**/
		public function Open($filename)
		{
			if(!file_exists($filename))
            {
                die("XML: Can't locate file: [ ".$filename." ]");
            }
			if(!$this->m_handle = simplexml_load_file($filename))
            {
				throw new \Exception("XML: Error in parsing file: [ ".$filename." ]");
            } 
			$this->m_filename = $filename;
			return true;			
		}
        
        /**
         * Saving array as xml file
         * @static
         * @param string file - path to file
         * @param string opentag - opening tag name
         * @param array $data  - data to save
         */
        static public function Save($file, $opentag, array $data=array())
        {
            if(empty($data))
            {
                throw new \Exception("XML: Missing data to save in file: ".$filename);
            }
            
            $xml = '<?xml version="1.0" encoding="UTF-8"?>'."\n";
            $xml .= '<'.$opentag.'>'."\n";
            foreach($data as $k => $v)
            {
                $xml.="\t".'<'.$k.'>'.$v.'</'.$k.'>'."\n";
            }
            $xml .= '</'.$opentag.'>'."\n";
            
            $fp = fopen(BASE_PATH.$file, "w+");
            fwrite($fp, $xml);
            fclose($fp);
            
            return true;
        }
        
		
		/** Get variable
		**/
		public function __get($data)
		{
			return $this->m_handle->{$data};
		}
				
	}
}
?>